package com.szaupd.config.job;

import com.szaupd.dao.DateRepository;
import com.szaupd.entity.Date;
import com.szaupd.utils.DateUtils;
import com.szaupd.utils.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
@EnableScheduling
public class DateJob {
    @Resource
    private DateRepository dateRepository;
    @Resource
    private IdUtils idUtils;

    private static final int INIT_DATE = 20200110;


    @Scheduled(initialDelay = 2000, fixedDelayString = "30000")
    public void DateJob() {

        List<Date> all = dateRepository.findAll(Sort.by(Sort.Direction.DESC, "date"));
        if (all == null || all.size() == 0) { //如果为空
            createDate(INIT_DATE); //生成数据
        } else {
            Date date = all.get(0);
            log.info("最新日期为" + date);
            if (date.getDate() != DateUtils.getYesterday()) {
                createDate(date.getStatus()==1?DateUtils.addOneDay(date.getDate()):date.getDate());
            }
        }
    }

    private void createDate(int initDate) {
        boolean flag = true;
        int tmpDate = initDate;
        while (flag) {
            Date date = Date.builder()
                    .id(idUtils.nextId())
                    .date(tmpDate)
                    .status(0)
                    .build();
            dateRepository.save(date);
            tmpDate = DateUtils.addOneDay(tmpDate);
            if (tmpDate >= DateUtils.getToday()) {
                flag = false;
            }
        }
    }
}
